package com.vogue.supplymall.account.shiro.realm;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.vogue.supplymall.account.domain.model.User;
import com.vogue.supplymall.account.domain.service.UserService;
import com.vogue.supplymall.account.shiro.bean.PasswordBean;
import com.vogue.supplymall.account.shiro.token.SwitchingIdentityToken;
import com.vogue.supplymall.match.domain.service.MatchOrganService;
import com.vogue.supplymall.shop.domain.service.ShopService;
/**
 * 登录人切换身份自动登录
 * 
 * @author 崔岳
 *
 */
public class SwitchingIdentityRealm extends AccountBaseAuthorizingRealm{

	public static final Logger LOGGER_SWITCHINGIDENTITYREALM = LoggerFactory.getLogger(SwitchingIdentityRealm.class);
	
	@Autowired
	private UserService userService;
	
	@Resource
	private MatchOrganService matchOrganService;

	@Resource
	private ShopService shopService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		Set<String> set = new HashSet<String>();
		set.add("admin");
		authorizationInfo.setRoles(set);
		set = new HashSet<String>();
		set.add("*:*:*");
		authorizationInfo.setStringPermissions(set);
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		SwitchingIdentityToken upToken = (SwitchingIdentityToken) token;
		String username = upToken.getUsername();
		PasswordBean bean= new PasswordBean();
		Map<String, Object> pwdmap = bean.newPassword(username, upToken.getPassword());
//		CredentialsMatcher match = (CredentialsMatcher)this.getCredentialsMatcher();

		if(StringUtils.isEmpty(username)) {
			throw new UnknownAccountException();
		}
		
		User user = userService.selectOneByWhr("tel = '"
				+ username + "'");
		
		// 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				loginInfo(user), // 用户名
				pwdmap.get(PasswordBean.MAP_KEY_NEWPWD), // 密码
				getName() // realm name
		);
		return authenticationInfo;
	}

	@Override
	public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
		super.clearCachedAuthorizationInfo(principals);
	}

	@Override
	public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
		super.clearCachedAuthenticationInfo(principals);
	}

	@Override
	public void clearCache(PrincipalCollection principals) {
		super.clearCache(principals);
	}

	public void clearAllCachedAuthorizationInfo() {
		if (getAuthorizationCache() != null) {
			getAuthorizationCache().clear();
		}

	}

	public void clearAllCachedAuthenticationInfo() {
		if (getAuthenticationCache() != null) {
			getAuthenticationCache().clear();
		}
	}

	public void clearAllCache(PrincipalCollection principals) {
		clearCachedAuthorizationInfo(principals);
		clearCachedAuthenticationInfo(principals);
	}

	/**
	 * 描述：获取某个登录人得相关缓存的键值 <br>
	 * 参数：principal 登录人的唯一认证标志 <br>
	 * 返回值：返回值说明 <br>
	 * 作者：崔岳，天津风行科技信息工程有限公司 <br>
	 * 创建日期：2016年1月14日 <br>
	 *************************************************************************************************/
	public static String getCacheKey(String principal) {
		if(SecurityUtils.getSubject() != null && SecurityUtils.getSubject().getSession() != null) {
			return principal + SecurityUtils.getSubject().getSession().getId();
		}else {
			return principal;
		}	
	}

	public boolean supports(AuthenticationToken token) {
		return token != null && SwitchingIdentityToken.class.isAssignableFrom(token.getClass());
	}
}
